package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.math.BigDecimal;

import static com.shanxia.codec.CodeConstant.HUNDRED;
import static com.shanxia.codec.CodeConstant.PERCENT;
import static com.shanxia.codec.Decoder.*;

/**
 * S -> C
 * 后台服务器应答桩上传命令请求
 * 后台服务器向充电桩数据请求命令
 */
@Data
public class Cmd9 extends ProtocolDataBase {

    public static final int MIN_SIZE = 17;

    private int v1;
    private int v2;
    private int pileNum;                     // 充电枪号
    private int code;                        // 执行结果
    private int requestAddr;                 // 命令地址
    private int dataLen;                     // 数据长度
    private String data;                     // 数据

    public Cmd9(){
        super.setCmd(9);
    }

    public static Cmd9 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd9 cmd = new Cmd9();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 1字节充电枪号
        cmd.pileNum = getUint8(dataField[offset++]);
        // 4字节执行结果
        cmd.code = bytesToIntLittle(dataField, offset);
        offset += 4;
        // 4字节命令地址
        cmd.requestAddr = bytesToIntLittle(dataField, offset);
        offset += 4;
        // 4字节数据长度
        cmd.dataLen = bytesToIntLittle(dataField, offset);
        offset += 4;
        // N字节数据
        switch (cmd.requestAddr) {
            // 4字节请求生成预付费支付二维码, 单位0.01元
            case 1:
            // 4字节预留，单位0.01元
            case 2:
                int amount = bytesToIntLittle(dataField, offset);
                cmd.data = String.valueOf(new BigDecimal(amount).multiply(PERCENT).doubleValue());
                break;
            default:
                break;
        }
        return cmd;
    }

    public byte[] getDataField() {
        int offset = 0;
        byte[] data = new byte[MIN_SIZE + this.dataLen];
        getBytesAsUint16(data, offset, this.v1);
        offset += 2;
        getBytesAsUint16(data, offset, this.v2);
        offset += 2;
        // 1字节充电枪号
        data[offset++] = (byte) this.pileNum;
        // 4字节执行结果
        intToBytesLittle(data, offset, this.code);
        offset += 4;
        // 4字节命令地址
        intToBytesLittle(data, offset, this.requestAddr);
        offset += 4;
        // 4字节数据长度
        intToBytesLittle(data, offset, this.dataLen);
        offset += 4;
        // N(4)字节参数
        int value = new BigDecimal(this.data).multiply(HUNDRED).intValue();
        intToBytesLittle(data, offset, value);
        return data;
    }
}
